<script setup>
import {ref} from 'vue'
import {get, post} from '../util/request.js'
import {useStore} from "../pinia/index.js";
import {useRouter} from "vue-router";
import { showToast } from 'vant';
const router=useRouter();
const store=useStore();
const user=ref({})
const login=()=>{
  var url="user/loginpass";
  if(!type.value){
    //验证码登录
    url="user/logincode";
  }
  //请求接口
  post(url,user.value).then(r=>{
    if(r.code==0){
      //登录成功 令牌 保存
      store.setToken(r.data);
      //跳转
      router.push("/home");

    }else {
      showToast(r.data);
    }
  })
}
//true 密码，false 验证码
const type=ref(true);
const lbname=ref("账号");
const changeTab = (e) => {
  user.value={};
  if(e.name=="0"){
    //密码登录
    type.value=true;
    lbname.value="账号";
  }else {
    //验证码登录
    lbname.value="手机号";
    type.value=false;

  }
}

const sendCode = () => {
  //发送短信验证码
  get("sms/sendlcode",{phone:user.value.name}).then(r=>{
    if(r.code==0){  // 0表示成功   1表示拜拜   2  3
      showToast('验证码已发送你手机，请查收！');
    }else {
      showToast(r.data);
    }
  })
}

</script>

<template>
  <van-nav-bar title="欢迎登录LoveCall" />
  <div>

    <div style="text-align: center">
      <van-image
          round
          width="10rem"
          height="10rem"
          src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
      />
    </div>
    <van-tabs @click-tab="changeTab">
      <van-tab >
        <template #title>
          <van-icon name="browsing-history" />密码登录</template>

      </van-tab>
      <van-tab >
        <template #title>
          <van-icon name="comment-circle" />验证码登录 </template>

      </van-tab>
    </van-tabs>
    <van-form @submit="login">
      <van-cell-group inset>
        <van-field
            v-model="user.name"
            :label="lbname"
            placeholder="请输入账号或手机号"
            :rules="[{ required: true, message: '请输入账号或手机号' }]"
        />

        <!-- 输入密码 -->
        <van-field
            v-if="type"
            v-model="user.pass"
            :rules="[{ required: true, message: '请输入密码' }]"
            type="password" placeholder="请输入密码" label="密码" />
        <van-field
            v-model="user.pass"
            center
            v-else
            :rules="[{ required: true, message: '请输入短信验证码' }]"
            clearable
            label="短信验证码"
            placeholder="请输入短信验证码"
        >
          <template #button>
            <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin-left: 10%;width: 80%">
        <van-button type="success" round block native-type="submit">登录账号</van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>

</style>
